package com.shiguiwu.springboot3.gateway.filter;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shiguiwu.springboot3.util.R;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static org.springframework.cloud.gateway.filter.WebClientWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER;

/**
 * 响应体转换处理
 * @author heguitang
 */
@Component
@Slf4j
public class HttpResponseBodyGlobalFilter implements GlobalFilter, Ordered {


    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public int getOrder() {
        // -1 is response write filter, must be called before that
        return WRITE_RESPONSE_FILTER_ORDER - 2;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("global filter HttpResponseBody，processing response results");

        // 这里可以增加一些业务判断条件，进行跳过处理

        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();
        // 响应装饰
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                log.info("global filter HttpResponseBody，Response processing，getStatusCode={}", getStatusCode());
                if (getStatusCode() != null && body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(
                            fluxBody.buffer()
                                    .map(dataBuffers -> {
                                // 如果响应过大，会进行截断，出现乱码，看api DefaultDataBufferFactory
                                // 有个join方法可以合并所有的流，乱码的问题解决
                                DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                                DataBuffer dataBuffer = dataBufferFactory.join(dataBuffers);
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                // 释放掉内存
                                DataBufferUtils.release(dataBuffer);
                                if (content.length == 0) {
                                    return bufferFactory.wrap(content);
                                }
                                String result = new String(content, StandardCharsets.UTF_8);
                                R<?> ok = null;

                                if (!JSONUtil.isTypeJSON(result)) {
                                    ok = R.ok(result);
                                } else {
                                    try {
                                        ok = objectMapper.readValue(content, R.class);
                                        if (null == ok.getCode()) {
                                            ok = R.ok(objectMapper.readValue(content, Object.class));
                                        }
                                    } catch (IOException e) {
                                        log.error("网关对象装换异常 {}", result, e);
                                    }

                                }
                                byte[] uppedContent = JSONUtil.toJsonStr(ok).getBytes(StandardCharsets.UTF_8);
                                response.getHeaders().setContentLength(uppedContent.length);
                                response.setStatusCode(HttpStatus.OK);

                                return bufferFactory.wrap(uppedContent);
                            }));
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
        // replace response with decorator
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }


}
